package jh.com.jhappbf.dispatchcar;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.pullview.AbPullToRefreshView;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import java.util.ArrayList;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.model.PihaoModel;
import jh.com.jhappbf.utils.JsonHelper;

/**
 * @author Administrator
 */
public class ContractSelectPihaoBuy extends AbActivity{
    private View mNetErrorView;
    private View mDataContentView;
    private AbPullToRefreshView mRefreshView;
    private ListView mListView;
    private Button mTryAgain;
    private Context mAppContext;
    private ArrayList<PihaoModel> pihaoModels;

    private MyBaseAdapter mAdapter;
    private AbDialogFragment mDialogFragment;
    private String companyCode;
    private String cargonameId;
    private String danhao;
    private String hanghao;
    private String danwei;
    private String mType;
    private String initGross;
    private String flag;
    private TextView cargonameIdTxt;
    private TextView companyCodeTxt;
    private TextView initGrossTxt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDataContentView = View.inflate(ContractSelectPihaoBuy.this, R.layout.dispatch_car_query_activity_item, null);
        mNetErrorView = View.inflate(ContractSelectPihaoBuy.this, R.layout.net_error_activity, null);
        setAbContentView(mDataContentView);
        AbTitleBar mAbTitleBar = this.getTitleBar();
        companyCode=getIntent().getStringExtra("CompanyCode");
        cargonameId=getIntent().getStringExtra("cargonameId");
        danhao=getIntent().getStringExtra("danhao");
        hanghao=getIntent().getStringExtra("hanghao");
        danwei=getIntent().getStringExtra("danwei");
        initGross=getIntent().getStringExtra("initGross");
        mType=getIntent().getStringExtra("mType");
        flag=getIntent().getStringExtra("flag");
        pihaoModels= (ArrayList<PihaoModel>) getIntent().getSerializableExtra("PihaoModels");
        mAbTitleBar.setTitleText("选择库存");
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
        mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mAbTitleBar.setLogoLine(R.mipmap.line);
        mAbTitleBar.setLogoOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        View rightViewMore = mInflater.inflate(R.layout.title_right_ok_btn_view, null);
        mAbTitleBar.addRightView(rightViewMore);
        Button mTitleRightBtn = rightViewMore.findViewById(R.id.title_right_ok_btn);
        mTitleRightBtn.setOnClickListener(v -> {
            confirmSelect();
        });
        initView();
    }
    /**
     * 保存
     */
    private void confirmSelect() {
//        Double allNum=0.0;
//        Double initGrossD=Double.parseDouble(initGross);
//        for (PihaoModel pihaoModel:pihaoModels) {
//            if (pihaoModel.isChk()){
//                allNum+=Double.parseDouble(pihaoModel.getNum());
//            }
//        }
//        if ((allNum-initGrossD>0)&&!TextUtils.isEmpty(flag)){
//            AbToastUtil.showToast(this,"确认数量与订单数量不符");
//        }else {
            Intent i = new Intent();
            i.putExtra("pihaoModels",pihaoModels);
            setResult(3, i);
            this.finish();

//        }

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 初始化界面
     */
    private void initView() {
        mListView = mDataContentView.findViewById(R.id.dispatch_query_listView);
        cargonameIdTxt = mDataContentView.findViewById(R.id.cargoname_id);
        companyCodeTxt = mDataContentView.findViewById(R.id.company_id);
        initGrossTxt = mDataContentView.findViewById(R.id.init_gross);
        cargonameIdTxt.setText(cargonameId.substring(10));
        companyCodeTxt.setText(companyCode);
        initGrossTxt.setText(initGross);
        mRefreshView = mDataContentView.findViewById(R.id.dispatch_query_pullToRefreshView);
        mTryAgain = mNetErrorView.findViewById(R.id.network_error_btn);
        mAppContext = getApplicationContext();

        mAdapter = new MyBaseAdapter();
        mListView.setAdapter(mAdapter);

        mTryAgain.setOnClickListener(v -> {
            setAbContentView(mDataContentView);
            loadFirst();
        });
        mRefreshView.setOnHeaderRefreshListener(view -> refreshTask());
        if (pihaoModels==null){
            pihaoModels=new ArrayList<>();
            loadFirst();
        }
        else {
            mAdapter.notifyDataSetChanged();
        }
        mRefreshView.setOnFooterLoadListener(view -> mRefreshView.onHeaderRefreshFinish());


    }

    /**
     * 第一次加载
     */
    private void loadFirst() {
        mDialogFragment = AbDialogUtil.showLoadDialog(this, R.mipmap.ic_load,
                "查询中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(this::refreshTask);
    }

    /**
     * 上拉刷新
     */
    private void refreshTask() {
        String methodName = "queryUnloadDispatchlib";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("companyCode");
        param.add("cargonameId");
        value.add(companyCode);
        value.add(cargonameId);

        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(ContractSelectPihaoBuy.this);
            mRefreshView.onHeaderRefreshFinish();
            pihaoModels= JsonHelper.getEntityFromJson(response,PihaoModel.class);
            if (pihaoModels != null) {
                mAdapter.notifyDataSetChanged();
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(ContractSelectPihaoBuy.this);
            mRefreshView.onHeaderRefreshFinish();
            setAbContentView(mNetErrorView);
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(getApplicationContext()).addRequest(
                webService);
    }


    private int currentEditPosition  = -1;
    class MyBaseAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return pihaoModels!=null?pihaoModels.size():0;
        }

        @Override
        public Object getItem(int position) {
            return pihaoModels.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final int index=position;
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(ContractSelectPihaoBuy.this,R.layout.list_view_item_txt_check_lib, null);
                holder = new ViewHolder();
                holder.txt = convertView.findViewById(R.id.list_view_item_txt);
                holder.ckx=convertView.findViewById(R.id.list_view_item_check);
                holder.ext=convertView.findViewById(R.id.list_view_item_ext);
                holder.ll=convertView.findViewById(R.id.commit_ll);
                convertView.setTag(holder);
                holder.ckx.setTag(index);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.ext.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch(event.getAction()){
                        case  MotionEvent.ACTION_UP:
                            currentEditPosition = position;
                            break;
                    }
                    return false;
                }
            });
            String symbol = "\r\n";
            PihaoModel pihaoModel = pihaoModels.get(position);
            StringBuilder builder=new StringBuilder();
            builder.append("日期："+ pihaoModel.getLWEDT());
            builder.append(symbol);
            builder.append("库位："+ pihaoModel.getLGORT()+ "  批次："+ pihaoModel.getCHARG());
            builder.append(symbol);
            builder.append("数量："+ pihaoModel.getATP());
            holder.txt.setText(builder);
            if (pihaoModel.isChk()){
                holder.ckx.setChecked(true);
            }else {
                holder.ckx.setChecked(false);
            }
            if (!TextUtils.isEmpty(flag)){
                //定额
                holder.ext.setText(pihaoModel.getNum());
                holder.ext.clearFocus();
                if (currentEditPosition == position) {
                    holder.ext.requestFocus();  //重新获取焦点
                    holder.ext.setSelection(holder.ext.getText().length()); //设置光标位置
                }
                holder.ext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (hasFocus){
                            holder.ext.addTextChangedListener(textWatcher);
                        }else {
                            holder.ext.removeTextChangedListener(textWatcher);
                        }
                    }
                });
            }else {
                holder.ext.setText(initGross);
                pihaoModels.get(position).setNum(initGross);
                holder.ll.setVisibility(View.GONE);
            }

            holder.ckx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked){
                        try {
                            double a=pihaoModels.get(position).getATP();
                            double c=Double.parseDouble(initGross);
                            if (TextUtils.isEmpty(pihaoModels.get(position).getNum())||a<c){
                                AbToastUtil.showToast(ContractSelectPihaoBuy.this,"库存数量不够！");
                                pihaoModels.get(position).setChk(false);
                                holder.ckx.setChecked(false);
                            }else {
                                    for (PihaoModel pihaoModel:pihaoModels) {
                                        pihaoModel.setChk(false);
                                    }
                                    pihaoModels.get(position).setChk(true);
                                    pihaoModels.get(position).setDanhao(danhao);
                                    pihaoModels.get(position).setHanghao(hanghao);
                                    pihaoModels.get(position).setDanwei(danwei);
                                    pihaoModels.get(position).setBy1(mType);

                                    notifyDataSetChanged();


                            }
                        }catch (Exception e){
                            AbToastUtil.showToast(ContractSelectPihaoBuy.this,"请填写正确确认数量"+e.toString());
                        }

                    }else {
                        pihaoModels.get(position).setChk(false);

                    }
                }
            });
            return convertView;
        }
    }

    class ViewHolder {
        public TextView txt;
        public EditText ext;
        public CheckBox ckx;
        public LinearLayout ll;
    }
    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            pihaoModels.get(currentEditPosition).setNum(s.toString());

        }
    };
    @Override
    public void onBackPressed() {
        finish();
    }
}
